package net.forty2ware.vintagesofa

import org.apache.commons.lang.builder.EqualsBuilder
import org.apache.commons.lang.builder.HashCodeBuilder

// http://wiki.apache.org/couchdb/HTTP_Document_API
class Document {
  protected Database database
  private CouchDbHelper couchDbHelper = new CouchDbHelper()
  def name
  def revision
  def data

  def refresh() {
    data = [:]
  }

  def create() {
    def id = name ?: ''
    def response = couchDbHelper.post(database, id, data)
    if (response.ok) {
      name = response.id
      revision = response.rev
    }
    return response
  }

  def update() {
    return true
  }

  def delete() {
    return true
  }

  def copy(destinationname, destinationrevision) {
    if (destinationName instanceof Map) {
      def map = destinationName
      destinationName = map.name
      destinationRevision = (databaseRevision) ?: map.revision
    }

    return true
  }

  def move(destinationname, destinationrevision) {
    if (destinationName instanceof Map) {
      def map = destinationName
      destinationName = map.name
      destinationRevision = (databaseRevision) ?: map.revision
    }

    // doit

    name = destinationName
    revision = destinationRevision

    return true
  }
   
  def getUrl() {
    return couchDbHelper.getDatabaseUrl(database, "${name}?rev=${revision}")
  } 

  @Override
  public boolean equals(Object o) {
    if (o == null) { return false; }
    if (o == this) { return true; }
    if (obj.getClass() != getClass()) {
      return false;
    }

    Document rhs = (Document)o;
    return new EqualsBuilder()
      .append(database, rhs.database)
      .append(name, rhs.name)
      .append(revision, rhs.revision)
      .isEquals()
  } 

  @Override
  public int hashCode() {
    return new HashCodeBuilder(1, 187)
      .append(database)
      .append(name)
      .append(revision)
      .toHashCode()
  }

}
